package com.ec.service.impl;


import java.awt.EventQueue;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.ec.event.ECEvent;
import com.ec.event.ECEventListener;
import com.ec.event.ECEventType;
import com.ec.service.ECEventService;

/**
 * 事件服务实现
 * 
 * @ClassName: ECEventServiceImpl.java
 * @Description: TODO(检查调用线程，如果不是在Swing线程就加入到事件线程中调用 )
 * @author 笑笑
 * @version V1.0
 * @Date 2014年4月15日 下午11:07:51
 */
public class ECEventServiceImpl implements ECEventService {

	private Map<ECEventType, List<ECEventListener>> lookup;

	@Override
	public void register(ECEventType[] intrestedEvents, ECEventListener listener) {
		for (ECEventType type : intrestedEvents) {
			List<ECEventListener> list = lookup.get(type);
			if (list == null) {
				list = new ArrayList<ECEventListener>();
				lookup.put(type, list);
			}
			list.add(listener);
		}
	}

	@Override
	public void unregister(ECEventType[] intrestedEvents,
			ECEventListener listener) {
		for (ECEventType type : intrestedEvents) {
			List<ECEventListener> list = lookup.get(type);
			if (list != null) {
				lookup.remove(type);
			}
		}
	}

	@Override
	public void unregister(ECEventListener listener) {
		unregister(lookup.keySet().toArray(new ECEventType[0]), listener);
	}

	@Override
	public void broadcast(final ECEvent event) {
		if (EventQueue.isDispatchThread()) {
			doBroadcast(event);
		} else {
			EventQueue.invokeLater(new Runnable() {
				public void run() {
					doBroadcast(event);
				}
			});
		}
	}

	@Override
	public Object query(ECEvent event) throws Exception {
		List<ECEventListener> list = lookup.get(event.getType());
		if(list != null && list.size() > 0){
			for(ECEventListener listener: list){
				listener.onECEvent(event);
				if(event.isQueryHandled()){
					return event.getResult();
				}
			}
		}
		throw new Exception("没有处理请求事件");
	}

	private void doBroadcast(ECEvent event) {
		List<ECEventListener> list = lookup.get(event.getType());
		if (list != null && list.size() > 0) {
			list = new ArrayList<ECEventListener>(list);
			for (ECEventListener listener : list) {
				try {
					listener.onECEvent(event);
					/**
					 * if(event.isCancelBubble()){ return; }
					 */
				} catch (Throwable e) {
					System.out.println("广播事件错误!" + e.getStackTrace());
				}
			}
		}

	}

}
